﻿namespace BBCore.Server.Components.Pages.Admins
{
    public partial class LogsViewer
    {
        private const int MaxLines = 1000;//只显示最后 1000 行

        private string? _logContent;
        private async Task HandleFileSelectedAsync(string filePath)
        {
            if (File.Exists(filePath))
            {
                // 读取日志文件内容并显示
                //_logContent = await File.ReadAllTextAsync(filePath);//当日志文件被其他进程占用时，File.ReadAllText 方法会抛出异常
                try
                {
                    using FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    using StreamReader sr = new StreamReader(fs);
                    //_logContent = await sr.ReadToEndAsync();
                    var lines = new List<string>();
                    while (!sr.EndOfStream)
                    {
                        lines.Add(await sr.ReadLineAsync() ?? "");
                        if (lines.Count > MaxLines)
                            lines.RemoveAt(0); // 只保留最后MaxLines行
                    }
                    _logContent = string.Join('\n', lines);
                }
                catch (Exception ex)
                {
                    _logContent = $"读取文件时出错: {ex.Message}";
                }               
            }            
        }
    }
}
